home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: miker3@ix.netcom.com (Mike Rubenstein)
- Newsgroups: comp.lang.c
- Subject: Re: How to tell if a file exists in C
- Date: Thu, 15 Feb 1996 03:32:07 GMT
- Organization: Netcom
- Message-ID: <3122a294.94201494@nntp.ix.netcom.com>
- References: <4eqkj6$ipo@charm.magnus.acs.ohio-state.edu> <4eqn9q$dr1@sparcserver.lrz-muenchen.de> <3121db3e.43150046@nntp.ix.netcom.com> <4ftpnk$i74@cafu.fl.net.au>
- NNTP-Posting-Host: ix-dc14-24.ix.netcom.com
- X-NETCOM-Date: Wed Feb 14 7:32:06 PM PST 1996
- X-Newsreader: Forte Agent .99d/32.182
-
- als@fl.net.au (Andrew Snow) wrote:
-
- > miker3@ix.netcom.com (Mike Rubenstein) wrote:
- >
- > >ua302aa@sun2.lrz-muenchen.de (Kurt Watzka) wrote:
- >
- > >> xiaoyi@bmecg.bme.ohio-state.edu (Xiaoyi Wu) writes:
- > >>
- > >> >Hi, how do I find out if a file already exists
- > >> >in UNIX C? On PCs I would do a findfirst/findnext,
- > >> >is there an equivalent on Unix?
- > >>
- > >> Yes, there is an equivalent in a POSIX environment, but there
- > >> is a portable solution in C, too. The fopen()-function can
- > >> be used to decide whether a file is accessible for reading,
- > >> and if it is not accessible for reading, errno can be used
- > >> to detect the reason for that.
- >
- > >Unfortunately, this is not portable. Nothing in the C standard
- > >requires fopen() to set errno to a sensible value (or, for that
- > >matter, to set it at all) if there is an error.
- >
- > How about plain old:
- >
- > if(0==access("filename", F_OK))
- > {
- > do stuff with file();
- > }
- > else
- > {
- > error();
- > }
- >
- > This works O.K. under Linux and FreeBSD, and most DOS compilers.
- >
- > If you want to see if the file is readable as well as exists,
- > use if(0==access("filename", F_OK | R_OK))
- > ...
- >
- > or writeable, use F_OK | R_OK | W_OK
- >
- >
- > and so on.
-
- In many cases that would be my preference. In others, where true
- portability is important, I'd go with using fopen(), but without
- checking errno to determine the cause if it fails.
-
- While it's true that access() is defined on many systems, there's more
- needed for portability. Header files that are needed are not
- standardized. Also there are some differences in implementations.
- Microsoft (VC++ 4.0) for example calls the function _access and does
- not define F_OK, etc.
-
-
- Michael M Rubenstein
-